package jdk8;

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.junit.Test;

import jdk8.User;

public class TestComparableComparator {
    @Test
    public void comparableComparator() {
        List<String> sarrays = Arrays.asList("1", "3", "0", "7", "5", "4", "2", "6", "8", "9");
        //sarrays.stream().sorted((v1,v2)->v1.compareTo(v2)).forEach(System.out::printf);
        //sarrays.stream().sorted(new ComparableComparator()::compare).forEach(System.out::printf);
        //sarrays.stream().sorted(ObjectUtil::compare).forEach(System.out::printf);
        sarrays.stream().sorted().forEach(System.out::printf);

        //sarrays.stream().map(Integer::parseInt).sorted(Comparator::comparingInt);
    }

    /**
     * 倒序
     */
    @Test
    public void jdkSorted() {
        List<User> sarrays = Arrays.asList(new User(1, 18, "张三"), new User(2, 19, "李四"), new User(3, 20, "王五"), new User(4, 18, "六"));
        sarrays.stream().sorted(Comparator.comparing(User::getAge).reversed()).peek(u -> System.out.println(u)).collect(Collectors.toList());
    }

    /**
     * 多个字段排序
     */
    @Test
    public void thenComparing() {
        List<User> sarrays = Arrays.asList(new User(1, 18, "张三"), new User(2, 19, "李四"), new User(3, 20, "王五"), new User(4, 18, "六"));
        List<User> nUsers = sarrays.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getId)).collect(Collectors.toList());
        System.out.println(nUsers);
    }

    /**
     * 根据某字段去重
     */
    @Test
    public void distinct() {
        List<User> sarrays = Arrays.asList(new User(1, 18, "张三"), new User(1, 19, "李四"), new User(3, 20, "王五"), new User(4, 18, "六"));
        ArrayList<User> discUser = sarrays.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(User::getId))), ArrayList<User>::new));
        System.out.println(discUser);
    }
}
